#include  <Windows.h>
#include "GLcontext.h"
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#include <io.h>
#include <fcntl.h>
#include "Console.h"

#pragma comment (lib, "user32.lib")
#pragma comment(lib, "glew32.lib")  
#pragma comment(lib, "opengl32.lib") 
GLcontext gl;
HGLRC hrc; // Rendering context 
HDC hdc;
#define HEIGHT 800
#define WIDTH 600
#define _DEBUGNO
const TCHAR CLASS_NAME[] = _T("Doom"); //Windows class name;
const TCHAR WINDOW_TITLE[] = _T("Doom");//Application title
//static_assert(__cplusplus > 199711L, "Program requires C++11 capable compiler");

//Windows procedure function
LRESULT CALLBACK wndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
void SetupPixelFormat(HDC hdc);
void GetDesktopResolution(int& horizontal, int& vertical);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevIstance, LPSTR lpCmdLine, int nCmdShow)
{
#ifdef _DEBUG
	RedirectIOToConsole(); //cout do not work for it, only fprintf works.
	fprintf(stdout, "Starting program...\n");
#endif
	//1 - Create window class structure. It contains information about windows.
	WNDCLASSEX wcex;
	ZeroMemory(&wcex, sizeof(WNDCLASSEX));
	wcex.cbSize = sizeof(WNDCLASSEX);
	wcex.style = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc = wndProc;
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInstance;
	wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wcex.lpszMenuName = NULL;
	wcex.lpszClassName = CLASS_NAME;
	wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));

	//2 - Register windows class
	if (!RegisterClassEx(&wcex)){
		MessageBox(NULL, _T("Call to RegisterClassEx failed!"), _T("Win32 Guided Tour"), NULL);
		return 1;
	}

	//3 - Create windows
	HWND hwnd = CreateWindow(
		CLASS_NAME,
		WINDOW_TITLE,
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, CW_USEDEFAULT,
		HEIGHT, WIDTH,
		NULL,
		NULL,
		hInstance,
		NULL
		);
	if (!hwnd){
		MessageBox(NULL, _T("Call to CreateWindow failed!"), _T("Win32 Guided Tour"), NULL);
		return 1;
	}
	//4 - Following code display window
	ShowWindow(hwnd, nCmdShow);
	UpdateWindow(hwnd);
	gl = GLcontext::GLcontext();


	//5 - Create the message loop which will dispatch message to WndProc
	MSG msg;
	/* process messages */
	while (TRUE)
	{
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		if (msg.message == WM_QUIT)
			break;
	}
	return (int)msg.wParam;
}

LRESULT CALLBACK wndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg)
	{
	case WM_CREATE:
	{
		hdc = GetDC(hWnd); //// Get the device context for our window  
		SetupPixelFormat(hdc);
		gl.SetupScene();
		break;
	}
	case WM_PAINT:
	{
		gl.RenderScene();
		SwapBuffers(hdc); // Swap buffers so we can see our rendering 
		break;
	}
	case WM_DESTROY:
	{
		/* finish OpenGL rendering */
		if (hrc) {
			wglMakeCurrent(NULL, NULL);
			wglDeleteContext(hrc);
		}
		ReleaseDC(hWnd, hdc);
		PostQuitMessage(0);
		break;
	}
	case WM_SIZE:
		gl.ReshapeWindow(LOWORD(lParam), HIWORD(lParam)); // Send the new window size to our GLcontext
		break;
	case WM_KEYDOWN:
	{
		switch (wParam)
		{
		case VK_LEFT:
			gl.GetKey(1);
			break;
		case VK_RIGHT:
			gl.GetKey(2);
			break;
		default:
			break;
		}
	}
	default:
		return DefWindowProc(hWnd, msg, wParam, lParam);
		break;
	}
}

void SetupPixelFormat(HDC hdc)
{
	PIXELFORMATDESCRIPTOR pfd; // Create a new PIXELFORMATDESCRIPTOR (PFD)  
	memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); // Clear our  PFD  
	pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); // Set the size of the PFD to the size of the class  
	pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; // Enable double buffering, opengl support and drawing to a window  
	pfd.iPixelType = PFD_TYPE_RGBA; // Set our application to use RGBA pixels  
	pfd.cColorBits = 32; // Give us 32 bits of color information (the higher, the more colors)  
	pfd.cDepthBits = 32; // Give us 32 bits of depth information (the higher, the more depth levels)  
	pfd.iLayerType = PFD_MAIN_PLANE; // Set the layer of the PFD  
	int pixelFormat;

	pixelFormat = ChoosePixelFormat(hdc, &pfd);
	if (pixelFormat == 0) {
		MessageBox(WindowFromDC(hdc), _T("ChoosePixelFormat failed."), _T("Error"),
			MB_ICONERROR | MB_OK);
		exit(1);
	}

	if (SetPixelFormat(hdc, pixelFormat, &pfd) != TRUE) {
		MessageBox(WindowFromDC(hdc), _T("SetPixelFormat failed."), _T("Error"),
			MB_ICONERROR | MB_OK);
		exit(1);
	}

	HGLRC tempOpenGLContext = wglCreateContext(hdc); // Create an OpenGL 2.1 context for our device context  
	wglMakeCurrent(hdc, tempOpenGLContext); // Make the OpenGL 2.1 context current and active 

	GLenum error = glewInit(); // Enable GLEW  
	if (error != GLEW_OK) // If GLEW fails 
	{
		MessageBox(WindowFromDC(hdc), _T("Could not intiliaze GLEW."), _T("Error"),
			MB_ICONERROR | MB_OK);
		exit(1);
	}


	int attributes[] = {
		WGL_CONTEXT_MAJOR_VERSION_ARB, 4, // Set the MAJOR version of OpenGL to 4  
		WGL_CONTEXT_MINOR_VERSION_ARB, 3, // Set the MINOR version of OpenGL to 3  
		WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, // Set our OpenGL context to be forward compatible  
		0
	};

	if (wglewIsSupported("WGL_ARB_create_context") == 1) { // If the OpenGL 4.0 context creation extension is available  
		hrc = wglCreateContextAttribsARB(hdc, NULL, attributes); // Create and OpenGL 4.0 context based on the given attributes  
		wglMakeCurrent(NULL, NULL); // Remove the temporary context from being active  
		wglDeleteContext(tempOpenGLContext); // Delete the temporary OpenGL 2.1 context  
		wglMakeCurrent(hdc, hrc); // Make our OpenGL 4.0 context current  
	}
	else{
		hrc = tempOpenGLContext; // If we didn't have support for OpenGL 4.0 and up, use the OpenGL 2.1 context 
		MessageBox(WindowFromDC(hdc), _T("Could not intiliaze OpenGL 4.0. Switching to OpenGL 2.1"), _T("Error"),
			MB_ICONERROR | MB_OK);
	}
}

void GetDesktopResolution(int& horizontal, int& vertical)
{
	RECT desktop;
	// Get a handle to the desktop window
	const HWND hDesktop = GetDesktopWindow();
	// Get the size of screen to the variable desktop
	GetWindowRect(hDesktop, &desktop);
	// The top left corner will have coordinates (0,0)
	// and the bottom right corner will have coordinates
	// (horizontal, vertical)
	horizontal = desktop.right;
	vertical = desktop.bottom;
}
